package com.chen.interceptor;

import com.chen.bean.constants.WxConstants;
import com.chen.bean.entity.UserEntity;
import com.chen.bean.enums.ResultCode;
import com.chen.exception.BusinessException;
import com.chen.util.JsonMapper;
import com.chen.util.JwtHelper;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Component
public class WebSocketInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 判断请求类型并获取token
        if (request instanceof ServletServerHttpRequest servletRequest) {
            HttpServletRequest rawRequest = servletRequest.getServletRequest();
            // 从URL查询参数中获取token
            String token = rawRequest.getParameter(WxConstants.WX_LOGIN_TOKEN);
            if (StringUtils.isBlank(token)) {
                throw new BusinessException(ResultCode.UNAUTHORIZED);
            }

            // 验证token并获取用户信息
            String userInfoJson = JwtHelper.verifyTokenAndGetUserId(token);
            if (StringUtils.isBlank(userInfoJson)){
                throw new BusinessException(ResultCode.UNAUTHORIZED);
            }
            // 放入用户信息到attributes中
            UserEntity userEntity = JsonMapper.fromJson(userInfoJson, UserEntity.class);
            attributes.put(WxConstants.WX_WEBSOCKET_ATTRIBUTE, userEntity);
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
